package study.wy.queue;

/**
 * 未优化的队列结构
 * @author wy
 */
public class ArrayQueue<T> {
    private Object[] arrQueue;
    private int maxSize;
    private int front;
    private int rear;

    public ArrayQueue() {
        this(16);
    }

    public ArrayQueue(int maxSize) {
        this.maxSize = maxSize;
        this.front = -1;
        this.rear = -1;
        this.arrQueue = new Object[maxSize];
    }

    /**
     * 判断队列是否已满
     * @return  true：已满，false：未满
     */
    public boolean isFull(){
        return this.rear == this.maxSize - 1;
    }

    /**
     * 判断队列是否为空队列
     * @return  true：空队列，false：非空
     */
    public boolean isEmpty(){
        return this.rear == this.front;
    }

    /**
     * 向队列中添加元素
     * @param obj   需要添加的元素
     */
    public void add(T obj){
        //判断队列是否已满
        if (isFull()) {
            throw new RuntimeException("队列已满");
        }
        this.arrQueue[++this.rear] = obj;
    }

    /**
     * 从队列中取出元素
     * @return  取出的元素
     */
    public T get(){
        //判断队列是否为空队列
        if (isEmpty()) {
            throw new RuntimeException("队列已空");
        }
        return (T) this.arrQueue[++this.front];
    }

    /**
     * 展示队列中所有元素
     */
    public void show(){
        //判断队列是否是空队列
        if (isEmpty()) {
            throw new RuntimeException("队列已空");
        }
        for (int i = this.front + 1; i <= this.rear; i++) {
            System.out.println(arrQueue[i]);
        }
    }

    /**
     * 查看队首元素
     * @return  队首元素
     */
    public T head(){
        if (isEmpty()) {
            throw new RuntimeException("队列已空");
        }
        return (T) this.arrQueue[front+1];
    }
}
